<template>
    <div class="app-container">
      <div class="filter-container">
        <el-date-picker v-model="listQuery.selectMonth" type="month" placeholder="选择月"   
        @change="jobSearch" value-format="yyyy-MM" @keyup.enter.native="handleFilter" class="filter-item">
        </el-date-picker>
        <el-input class="filter-item" v-model="listQuery.announcementTitle" type="text" style="width: 220px;margin-left: 10px;"  placeholder="请输入要搜索的标题关键词" />
        <el-button v-waves class="filter-item" style="margin-left: 10px;"type="primary" icon="el-icon-search" @click="handleFilter">
          {{ $t('table.search') }}
        </el-button>
        <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
          添加公告
        </el-button>
      </div>
      <!--表格内容-->
      <el-table
        :key="tableKey"
        v-loading="listLoading"
        :data="list"
        border
        fit
        highlight-current-row
        style="width: 100%;"
        @sort-change="sortChange"
      >
        <el-table-column label="公告ID" prop="announcementId" 
        sortable="custom" align="center" width="80" :class-name="getSortClass('announcementId')">
          <template slot-scope="{row}">
            <span>{{ row.announcementId }}</span>
          </template>
        </el-table-column>

        <el-table-column label="公告标题" prop="announcementTitle" 
        sortable="custom" align="center" width="180" >
          <template slot-scope="{row}">
            <span>{{ row.announcementTitle }}</span>
          </template>
        </el-table-column>

        <el-table-column label="内容" prop="announcementText" 
        sortable="custom" align="center" width="200" >
          <template slot-scope="{row}">
            <span>{{  truncateText(row.announcementText, 10) }}</span>
          </template>
        </el-table-column>

        <el-table-column label="更新时间" prop="announcementAddTime" 
        sortable="custom" align="center" width="280" >
          <template slot-scope="{row}">
            <span>{{ row.announcementAddTime }}</span>
          </template>
        </el-table-column>

        <!--表格内部按钮-->
        <el-table-column :label="$t('table.actions')" align="center" width="230" class-name="small-padding fixed-width">
          <template slot-scope="{row,$index}">
            <el-button type="primary" size="mini" @click="handleUpdate(row)">
              {{ $t('table.edit') }}
            </el-button>
            <el-button v-if="row.status!='deleted'" size="mini" type="danger" @click="handleDelete(row,$index)">
              {{ $t('table.delete') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  
     <!--修改的表单-->
     <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
        <el-form ref="dataForm"  :model="temp" label-position="left" style="width: 90%; margin-left:50px;">

          <el-form-item label="公告标题">
            <el-input v-model="temp.announcementTitle" :autosize="{ minRows: 2, maxRows: 4}" type="text" placeholder="请输入标题" />
          </el-form-item>
          <el-form-item label="公告内容">
            <el-input v-model="temp.announcementText" :autosize="{ minRows: 2, maxRows: 10}" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">
            {{ $t('table.cancel') }}
          </el-button>
          <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
            {{ $t('table.confirm') }}
          </el-button>
        </div>
      </el-dialog>
  
      <el-dialog :visible.sync="dialogPvVisible" title="Reading statistics">
        <el-table :data="pvData" border fit highlight-current-row style="width: 100%">
          <el-table-column prop="key" label="Channel" />
          <el-table-column prop="pv" label="Pv" />
        </el-table>
        <span slot="footer" class="dialog-footer">
          <el-button type="primary" @click="dialogPvVisible = false">{{ $t('table.confirm') }}</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  import { findByPage,updatAnnouncement,addAnnouncement,deleteAnnouncement} from '@/api/announcement'
  import { findAllList } from '@/api/expensetype'
  import waves from '@/directive/waves' // waves directive
  import { parseTime } from '@/utils'
  import Pagination from '@/components/Pagination' // secondary package based on el-pagination
  export default {
    name: 'ComplexTable',
    components: { Pagination },
    directives: { waves },
    filters: {
    },
    data() {
      return {
        tableKey: 0,
        list: null,//表格集合数据
        total: 0,//总条数
        listLoading: true,
        listQuery: {//查询的筛选条件
          page: 1,
          limit: 10,
          selectMonth:this.getDefaultYearMonth(),
          announcementTitle:""
        },
        typeListLoad:[],
        typeListLoading: true,
        showReviewer: false,
        temp: {  //修改信息
          announcementId: undefined, 
          announcementTitle:"",
          announcementText:"",
          announcementAddTime:"",
        },
        dialogFormVisible: false,
        dialogStatus: '',
        textMap: {
          update: '修改公告',
          create: '添加公告'
        },
         dialogPvVisible: false,
        pvData: [],
         downloadLoading: false
      }
    },
    created() {//未渲染之前  data加载之后
      this.getList()
    },
    methods: {
      getList() {//获取 list  total
          this.listLoading = true;
          findByPage(this.listQuery).then(response => {
            this.list = response.data.list
            this.total = response.data.total
            console.log( response.data.list)
                setTimeout(() => {
                  this.listLoading = false
                }, 1.5 * 1000)  
           })         
      }, 
      gettypeList(){
          this.typeListLoading = true;
          findAllList().then(response => {
             this.typeListLoad=response.data
             console.log(this.typeListLoad);
             this.typeListLoading=false;
          })
    },       
      jobSearch() {
        this.getJobListByMonth();
        },
        async initData(data) {
      //获取当前时间
      var now   = new Date();
      var monthn = now.getMonth()+1;
      var yearn  = now.getFullYear();
      this.listQuery.selectMonth = yearn+"-"+monthn;
      this.selectUser = parseInt(sessionStorage.getItem("userid"));
      // this.getWeekJobList({
      //   userid: sessionStorage.getItem("userid"),
      //   weekid: "1"
      // });
        this.getJobListByMonth();
        },
    async getJobListByMonth(data) {
 
    },
        //截取文本内容的一部分
        truncateText(text, length) {
        if (text.length > length) {
          return text.slice(0, length)+'...';
        }
        return text;
      },
    getDefaultYearMonth() {
      // 获取当前年份
      const currentYear = new Date().getFullYear();
      // 获取当前月份（注意：月份是从0开始的，所以需要加1）
      const currentMonth = new Date().getMonth() + 1;
      // 将年份和月份格式化为字符串
      const formattedYear = currentYear.toString();
      const formattedMonth = currentMonth < 10 ? '0' + currentMonth : currentMonth.toString();
      // 组合成默认展示的年月
      return `${formattedYear}-${formattedMonth}`;
    },
      handleFilter() {
        this.listQuery.page = 1
        this.getList()
      },
      handleModifyStatus(row, status) {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        row.status = status
      },
      sortChange(data) {
        const { prop, order } = data
        if (prop === 'id') {
          this.sortByID(order)
        }
      },
      sortByID(order) {
        if (order === 'ascending') {
          this.listQuery.sort = '+id'
        } else {
          this.listQuery.sort = '-id'
        }
        this.handleFilter()
      },
      resetTemp() {
        this.temp = {
          announcementId: undefined, 
          announcementTitle: "",
          announcementText:"",
          announcementAddTime:"",
        }
      },
      handleCreate() {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },
      createData() {
      this.$refs['dataForm'].validate((valid) => {
        //判断验证是否通过
        if (valid) {   
          addAnnouncement(this.temp).then(response => {
            //把当前内容添加到 集合中
          // this.list.unshift(this.temp)
          this.getList();
           //设置是否被不通过
           this.dialogFormVisible = false
            this.$notify({
              title: '成功',
              message: '创建成功',
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
      handleUpdate(row) {
        this.temp = Object.assign({}, row) // copy obj
        this.dialogStatus = 'update'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      },

      updateData() {
        this.$refs['dataForm'].validate((valid) => {
          if (valid) {
            //临时数据   temp内容拷贝到tempData
            const tempData = Object.assign({}, this.temp)
            updatAnnouncement(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.temp.id)
              //替换
             // this.list.splice(index, 1, this.temp)
              this.dialogFormVisible = false
              this.getList();
              this.$notify({
                title: '成功',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        })
      },
      handleCreateType(typeAdd){
        createType(typeAdd).then(() => {
              this.getList();
              this.$notify({
                title: '成功',
                message: '费用类型添加成功',
                type: 'success',
                duration: 2000
              })
            })
      },
      handleDelete(row, index) {
        deleteAnnouncement(row.announcementId).then(() => {
              this.getList();
              this.$notify({
                title: '成功',
                message: '删除成功',
                type: 'success',
                duration: 2000
              })
            })
      },
      handleFetchPv(pv) {
        
      },

      formatJson(filterVal) {
        return this.list.map(v => filterVal.map(j => {
          if (j === 'timestamp') {
            return parseTime(v[j])
          } else {
            return v[j]
          }
        }))
      },
      getSortClass: function(key) {
        const sort = this.listQuery.sort
        return sort === `+${key}` ? 'ascending' : 'descending'
      }
    }
  }
  </script>
  